import request from './request'

/**
 *获取服务器地址
 */
export function getBaseUrl(isWs) {
  const env = process.env.VUE_APP_BASE_API
  const DESC = process.env.VUE_APP_ENV_DESC
  const HOSTS = {
    test: `${env}${isWs ? ':88/wss' : ':8007'}`,
    demo: `${env}${isWs ? ':88/wss' : ':8007'}`,
    newDemo: `${env}${isWs ? ':/wss' : ''}`,
    development: `${env}${isWs ? '/wss' : ':8007'}`,
    production: `${env}${isWs ? '/wss' : ''}`
  }

  const certificate = `${isWs ? 'ws' : 'http'}${['production', 'newDemo'].includes(DESC) ? 's' : ''}://`

  return certificate + HOSTS[DESC]
}

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function GET({ url, params }) {
  return request
    .get(url, { params })
    .then((res) => res)
    .catch((err) => Promise.reject(err.data))
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function POST({ url, data }) {
  return request
    .post(url, data)
    .then((res) => res)
    .catch((err) => Promise.reject(err.data))
}

/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function PUT({ url, data }) {
  return request
    .put(url, data)
    .then((res) => res)
    .catch((err) => Promise.reject(err.data))
}

/**
 * delete 方法，delete
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function DELETE({ url, params }) {
  return new Promise((resolve, reject) => {
    request
      .delete(url, {
        params
      })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}
